package com.y.core.shiro;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;

import com.alibaba.fastjson.JSON;
import com.y.core.constant.PlatForm;
import com.y.core.toolbox.ajax.RestResult;

public class RestAuthorizationFilter extends AccessControlFilter  {
	@Override
	protected boolean isAccessAllowed(ServletRequest arg0, ServletResponse arg1, Object arg2) throws Exception {
		// rest为无状态,shiro自带过滤器无法校验,所以写个空过滤器放行
		return false;
	}
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		RestResult rr=new RestResult();
		String access_token = request.getParameter("access_token");
		if(!StringUtils.isBlank(access_token)){
			Map<String, Object> tokens=PlatForm.getACCESS_TOKENS();
			boolean is_acss=tokens.containsValue(access_token);//是否通过验证
			if(is_acss){
				return true;
			}else{
				rr.addFail("access_token认证失败");
			}
		}else{
			rr.addFail("未包含access_token,认证失败.");
		}
		onLoginFail(response, JSON.toJSONString(rr));
		return false;
	}

	// 登录失败时默认返回401状态码
	private void onLoginFail(ServletResponse response,String data) throws IOException {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		httpResponse.getWriter().write(data);
	}
}
